package com.ztstkj.lzservices.exceptions

import android.util.Log
import com.ztstkj.lzservices.mmkvs.MmkvManager
import com.ztstkj.lzservices.networks.NetworkUtils
import com.ztstkj.lzservices.retrofits.ResponseResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.withContext
import java.net.UnknownHostException

suspend inline fun <T> apiCall(isSpeech:Boolean=true,crossinline call: suspend CoroutineScope.() -> ResponseResult<T>): ResponseResult<T> {
    return withContext(Dispatchers.IO) {
        val res: ResponseResult<T>
        try {
            if(!NetworkUtils.onLine){
                throw UnknownHostException()
            }
            res = call()
        } catch (e: Throwable) {
            e.printStackTrace()
            MmkvManager.addLog(LogConstant.REQUEST_ERROR, e.message.toString())
            // 请求出错，将状态码和消息封装为 ResponseResult
            return@withContext ApiException.build(e).toResponse<T>(isSpeech)
        }
        if(res.code==500) {
            MmkvManager.addLog(LogConstant.REQUEST_ERROR, "状态码500，"+res.msg)
        }
        if (res.code == ApiException.CODE_AUTH_INVALID) {
            Log.e("ApiCaller", "request auth invalid")
            // 登录过期，取消协程，跳转登录界面
            cancel()
        }
        return@withContext res
    }
}